package root.electronclass.electronclass.grade.rota

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.viewModels
import root.electronclass.electronclass.CommonActivity
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.FragmentClassRotaBinding
import root.electronclass.electronclass.databinding.FragmentClassRotaHeaderBinding
import root.electronclass.electronclass.databinding.FragmentClassRotaItemBinding
import root.electronclass.electronclass.ext.doOnSearch
import root.electronclass.electronclass.ext.onResult
import root.electronclass.electronclass.ext.showAvatar
import root.electronclass.electronclass.ext.toMMdd
import root.electronclass.electronclass.grade.model.ClassCurriculumItem
import root.electronclass.electronclass.grade.model.ClassRotaItem
import root.electronclass.electronclass.grade.repository.ClassRepository
import root.electronclass.electronclass.grade.viewmodel.WeekType
import root.electronclass.electronclass.other.AttestationActivity

/**
 * 值日表
 * @author Lokiy
 * @date 2023/2/11 13:21
 */
class ClassRotaFragment : ViewBindingFragment<FragmentClassRotaBinding>() {

    private val viewModel: ClassRotaViewModel by viewModels()
    private var lastSuccessTime = 0L
    private var currentWeekType = WeekType.CURRENT

    @SuppressLint("NotifyDataSetChanged")
    private val titleAdapter = BasicAdapter<ClassCurriculumItem, FragmentClassRotaHeaderBinding> { holder, item ->
        holder.binding.itemName.text = item.subject
        holder.binding.itemTime.text = item.startTime.toMMdd
        holder.binding.itemToday.isVisible = item.subject == "今天"
        holder.binding.root.isActivated = item.startTime != viewModel.selectDate.value && item.subject == "今天"
        holder.binding.root.isSelected = item.startTime == viewModel.selectDate.value
        holder.binding.root.setOnClickListener {
            notifyDataSetChanged()
            viewModel.loadData(date = item.startTime)
        }
    }
    private val adapter = BasicAdapter<ClassRotaItem, FragmentClassRotaItemBinding> { holder, item ->
        val color = (item.color ?: ClassRepository.rotasColors.random()).toColorInt()
        val key = binding.search.text.toString()
        val isSelect = key.isNotEmpty() && (item.name.contains(key) || item.dutyItem.contains(key))

        holder.binding.itemName.text = item.dutyItem
        holder.binding.itemName.backgroundTintList = ColorStateList.valueOf(color)
//        holder.binding.itemSign.text = if (item.hasSign) "已签到" else "签到"
//        holder.binding.itemSign.setBackgroundResource(if (item.hasSign) com.uuzuche.lib_zxing.R.color.transparent else root.electronclass.electronclass.R.drawable.bg_306eff_round)
//        holder.binding.itemSign.setTextColor(if (isSelect) 0xFF000000.toInt() else if (item.hasSign) color else -1)
//        holder.binding.itemSign.setOnClickListener {
//            if (item.hasSign) return@setOnClickListener
//            //TODO 签到
//            item.hasSign = true
//            notifyItemChanged(holder.adapterPosition)
//        }
        holder.binding.itemStudentName.text = item.name
        holder.binding.itemStudentNo.text = getString(R.string.class_student_no, item.userNo)
        if (isSelect) {
            holder.binding.itemAvatar
        }

        holder.binding.itemBg.isSelected = isSelect
        val colorStateList1 = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_selected), intArrayOf()), intArrayOf(color, -1))
        holder.binding.itemBg.backgroundTintList = colorStateList1
        holder.binding.itemAvatar.showAvatar(item.facePhoto, if (item.gender == 2) 2 else 3)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //
        fun updateWeekType(pointTo: Int) {
            val type = when (currentWeekType) {
                WeekType.CURRENT -> if (pointTo > 0) WeekType.NEXT else WeekType.LAST
                WeekType.NEXT -> if (pointTo > 0) WeekType.LAST else WeekType.CURRENT
                WeekType.LAST -> if (pointTo > 0) WeekType.CURRENT else WeekType.NEXT
            }
            currentWeekType = type
            binding.tvWeek.text = when (type) {
                WeekType.CURRENT -> getString(R.string.class_current_week)
                WeekType.NEXT -> getString(R.string.class_next_week)
                WeekType.LAST -> getString(R.string.class_last_week)
            }
            viewModel.loadData(currentWeekType)
        }

        binding.ivLeft.setOnClickListener {
            updateWeekType(-1)
        }

        binding.ivRight.setOnClickListener {
            updateWeekType(1)
        }
        binding.search.doOnSearch {
//            viewModel.load(text = it)
            adapter.notifyDataSetChanged()
            false
        }
        binding.search.doAfterTextChanged {
            adapter.notifyDataSetChanged()
        }

        binding.manageRotaItem.setOnClickListener {
            val intent = Intent(requireActivity(), AttestationActivity::class.java)
            startActivityForResult(intent, AttestationActivity.MANAGER_ROTA)

//            CommonActivity.startActivity(requireContext(), ClassManageRotaFragment::class.java)
        }

        binding.addAttendant.setOnClickListener {
            CommonActivity.startActivity(requireContext(), ClassAddAttendantFragment::class.java)
        }

        binding.headerRecycler.adapter = titleAdapter

        binding.recycler.adapter = adapter

        viewModel.weekData.observe(viewLifecycleOwner) {
            titleAdapter.notifyChanged(it)
        }
        viewModel.data.observe(viewLifecycleOwner) {
            adapter.notifyChanged(it)
            if (lastSuccessTime == 0L && it.isNotEmpty()) lastSuccessTime = System.currentTimeMillis()
//            if (it.isNotEmpty()) {
//                lifecycleScope.launch(CoroutineExceptionHandler()) {
//                    binding.recycler.smoothScrollToPosition(0)
//                }
//            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        onResult(requestCode, resultCode, data)
    }

    override fun onResume() {
        super.onResume()
        if (System.currentTimeMillis() - lastSuccessTime > 1 * 60 * 60 * 1000) {
            viewModel.loadData()
            lastSuccessTime = 0L
        }
    }
}
